package com.zeji.androidadvance.activity.videolist;

import android.annotation.SuppressLint;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import java.util.ArrayList;
import java.util.List;

public class VideoListAdapter extends FragmentStateAdapter {
    private final List<String> value = new ArrayList<>();
    private final List<VideoItemFragment> fragments = new ArrayList<>();
    private int nowPos = 0;

    public VideoListAdapter(@NonNull FragmentActivity fragmentActivity, ViewPager2 viewPager2) {
        super(fragmentActivity);
        fragments.add(new VideoItemFragment());
        fragments.add(new VideoItemFragment());
        fragments.add(new VideoItemFragment());

        initListener(viewPager2);
    }

    private void initListener(ViewPager2 viewPager2) {
        viewPager2.setAdapter(this);
        viewPager2.setCurrentItem(1);
        viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            int selectPos = 1;
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                for (VideoItemFragment itemFragment : fragments) {
                    itemFragment.setOffsetRatio(positionOffset);
                }
            }

            @Override
            public void onPageSelected(int position) {
                selectPos = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if (selectPos == 0) {
                    nowPos = getPreInd();
                    viewPager2.setCurrentItem(1, false);
                } else if (selectPos == 2) {
                    nowPos = getNextInd();
                    viewPager2.setCurrentItem(1, false);
                }
                refreshPageData();
            }
        });
    }

    private void refreshPageData() {
        fragments.get(0).setUrl(value.get(getPreInd()));
        fragments.get(1).setUrl(value.get(nowPos));
        fragments.get(2).setUrl(value.get(getNextInd()));
    }

    private int getPreInd() {
        return (nowPos - 1 + value.size()) % value.size();
    }

    private int getNextInd() {
        return (nowPos + 1) % value.size();
    }

    @SuppressLint("NotifyDataSetChanged")
    public void setValue(List<String> value) {
        this.value.clear();
        this.value.addAll(value);
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        return fragments.get(position);
    }

    @Override
    public int getItemCount() {
        return 3;
    }
}